from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.db.models import Max,Q,F,Min,Avg,Count,Sum
from django.contrib.auth.hashers import make_password,check_password
import datetime  #导入时间包
import time
import random
from utils.comm import send_message
from utils.comm import get_redis_conn
from .ser import *
from django.http import HttpResponse

# Create your views here.


#测试
class Text(APIView):
    def get(self,request):
        # coom = redis.Redis('localhost', port=6379) #换成分装方法代替
        coom = get_redis_conn()
        coom.setex('username', 5, '小米')  #5秒后消失需要注释这行 不然刷新一直有这行
        name = coom.get('username')
        return Response(name)

#添加新闻
class MNewmanage(APIView):
    def post(self,request):
        ser = MNewSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code": 20010})

    def get(self,request):
        cpage = request.GET.get('cpage')
        if cpage:
            new = MNew.objects.all()
            news = Paginator(new,2)
            new_cpage = news.page(cpage)
            ser = MNewSer(new_cpage,many=True)
            tpage = news.num_pages
            return Response({"code": 200, 'list': ser.data,'tpage':tpage})
        else:
            new = MNew.objects.all()
            ser = MNewSer(new,many=True)
            return Response({"code":200,'list':ser.data})


#添加广告
class Madvertisingmanage(APIView):
    def post(self, request):
        ser = MadvertisingmanageSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 20010})

    def get(self, request):
        cpage = request.GET.get('cpage')
        if cpage:
            advertising = Madvertising.objects.all()
            advertisings = Paginator(advertising, 2)
            advertisings_cpage = advertisings.page(cpage)
            ser = MadvertisingmanageSer(advertisings_cpage, many=True)
            tpage = advertisings.num_pages
            return Response({"code": 200, 'list': ser.data, 'tpage': tpage})
        else:
            advertising = Madvertising.objects.all()
            ser = MadvertisingmanageSer(advertising, many=True)
            return Response({"code": 200, 'list': ser.data})

#友情链接
class Friendlink(APIView):
    def post(self,request):
        link = request.GET.get('link')
        ser = MadvertisingmanageSer(data=request.data)
        if ser.is_valid():
            ser.save()
            # addlink = Madvertising.objects.all(id=link).frist()
            # addlink.count +=1
            # addlink.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 20010})


#美多 开始
import re
#注册页面
class Registermanage(APIView):
    def post(self,request):
#验证用户名
        #获取用户名
        username = request.data.get('username')
        #用户名是否为空
        if not username:
            return Response({'code':10010})
        #用户名是否符合规则 正则
        if not re.match('^\w{5,10}$',username):
            return Response({'code': 10011})
        #用户名是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 10012})
#验证密码
        # 获取密码
        password = request.data.get('password')
        # 密码是否为空
        if not password:
            return Response({'code': 10016})
        # 密码是否符合规则 正则
        if not re.match('^[a-zA-Z0-9]{8,20}$', password):
            return Response({'code': 10017})
        # 密码是否注册
        pas = User.objects.filter(password=password).first()
        if pas:
            return Response({'code': 10018})

#确认密码
        conpassword = request.data.get('conpassword')
        print(conpassword)
        if conpassword == password:
            return Response({'code':10019})
        else:
            return Response({"code":10020})

#验证手机号
        # 获取手机号
        mobile = request.data.get('mobile')
        # 手机号是否为空
        if not mobile:
            return Response({'code': 10013})
        # 手机号是否符合规则 正则
        if not re.match('^1[3-9]\d{9}$', mobile):
            return Response({'code': 10014})
        # 手机号是否注册
        mob = User.objects.filter(mobile=mobile).first()
        if mob:
            return Response({'code': 10015})


#验证收到的手机验证码
        veri = request.data.get('veri')
        coom = get_redis_conn()
        mo = coom.get(mobile)
        if mo:
            mo = str(mo,encoding='utf8')
            if veri == mo:
                return Response({"code": 10021})

        return Response({'code':200})

import redis
#发送短信
class SendManage(APIView):
    def post(self, request):
        #获取号码
        mobile = request.data.get('mobile')
        #获取uid
        uid = request.data.get('uid')
        #获取图形验证码
        uuidurl = request.data.get('uuidurl')
        #开启reids 获取uid的值
        coom =get_redis_conn()
        imguid = coom.get(uid)  #取出图形验证码
        if imguid:
            imguid = str(imguid,encoding='utf8')
            if uuidurl.lower() == imguid.lower():
                num = random.randint(1000, 9999)
                res = send_message(mobile, str(num), 1)
                print(res)
                code = 10010
                if res :
                    code = 200
                    #发送验证码后存入redis
                    coom = get_redis_conn()
                    coom.setex(mobile, 60, num)
                    return Response({'code': code})

        return Response({'code': 20010})


from utils.captcha.captcha import captcha
#打入jwt
import jwt
from MeiDuo import settings
#获取图片验证码
class CreatCaptcha(APIView):
    def get(self,request):
        #导用cpatcha  text是图片验证码中数字 img是字节流
        name,text,img =captcha.generate_captcha()
        #开启redis
        coom  = get_redis_conn()
        #获取图片验证码 uuid
        uuid = request.GET.get('uid')
        # print(uid)
        # print(text)
        #保存图形验码
        coom.set(uuid,text)  #set中前一个参数是键 后一个参数是值
        return HttpResponse(img,content_type='image/jpg')

#注册按钮提交数据
    def post(self,request):
        username = request.data.get('username')
        request.data['password'] = make_password(request.data.get('password'))
        ser = CreatCaptchaSer(data=request.data)
        if ser.is_valid():
            ser.save()
            #生成jwt
            token = jwt.encode({'data': {'username': username}}, settings.SECRET_KEY, algorithm='HS256')
            return Response({'code': 200,'token':token})
        return Response({'code': 20010})

#用户登录 login
class Loginmanage(APIView):
    def post(self,request):
        #获取用户密码
        username = request.data.get('username')
        password = request.data.get('password')
        #查找用户信息
        user = User.objects.filter(username = username).first()
        #如果有用户
        if user:
            #密码对比
            if check_password(password,user.password):
                #密码对比成功登录成功返回token
                token = jwt.encode({'data': {'username': username,'id':user.id}}, settings.SECRET_KEY, algorithm='HS256')
                return Response({'code': 200, 'token': token,'userid':user.id})
        #用户不存在返回
        else:
            return Response({'code':200,'mes':'用户不存在'})

#导包限制最大创建数
from utils.comm import ADDRESS_MAX_COUNT

#添加新地址
class AddressManage(APIView):
    #新地址提交
    def post(self,request):
        userid = request.data.get('user')
        total = Address.objects.filter(user_id=userid).count()
        if total == ADDRESS_MAX_COUNT:
            return Response({"code": 30010, 'mes': '已经超过最大限制了'})

        ser = AddressManageSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code':20020})

    #获取三级联动
    def get(self,request):
        pid = request.GET.get('pid')
        if not pid:
            #获取省
            areas = Area.objects.filter(parent_id__isnull = True).all()
        else:
            #获取市
            areas = Area.objects.filter(parent_id=pid).all()
        ser = AreaSer(areas, many=True)
        return Response({"code": 200, 'list': ser.data})

    #修改默认地址
    def put(self,request):
        id =request.GET.get('id')
        #通过id查询该条信息记录
        address = Address.objects.filter(id=id).first()
        # 根据userid和is_default=1更新is_default=0
        Address.objects.filter(user_id=address.user_id,is_default=1).update(is_default=0)
        # 把当前id设置成默认
        address.is_default = 1
        address.save()
        return Response({"code": 200})


#展示收货人 地址信息
class ConsigneeManage(APIView):
    def get(self,request):
        #添加一步 获取userid 计算用户有几个收货地址
        userid = request.GET.get('userid')
        add = Address.objects.filter(user_id=userid).all()
        ser = ShowaddressSer(add,many=True)
        total = Address.objects.filter(user_id=userid).count()
        return Response({"code": 200, 'list': ser.data,'total':total})


